<?php
/**
 * CompleXml Framework
 *
 * @category   CompleXml
 * @package    CompleXml_Handler
 * @copyright  Copyright (c) 2008 Andrey Kucherenko
 * @license    New BSD License
 * @version    0.1
 */
require_once 'CompleXml/Handler/Output/Abstract.php';
class CompleXml_Handler_Output_Xslt extends CompleXml_Handler_Output_Abstract {
	/**
	 * Path to templates
	 *
	 * @var string
	 */
	protected $_template_path;

	/**
	 * Debug flag
	 *
	 * @var boolean
	 */
	private $_is_debug = false;

	/**
	 * @return boolean
	 */
	public function getIsDebug() {
		return $this->_is_debug;
	}

	/**
	 * @param boolean $is_debug
	 */
	public function setIsDebug($is_debug) {
		$this->_is_debug = $is_debug;
	}

	protected function canBrowserXsltProccess($browser)
	{
		$info = get_browser($browser);
		$version = (float) $info->version;
		switch ($info->browser) {
			case 'Opera':
				if ($version>=9.0){
					return true;
				}
				break;
			case 'IE':
				if ($version>=6.0){
					return true;
				}
				break;
			case 'Firefox':
				if ($version>=2.0){
					return true;
				}
				break;
			default:
				return false;
				break;
		}
	}

	public function execute(CompleXml_Object_Abstract $Object) {
		if (! ($Object instanceof CompleXml_Object_HttpModel)) {
			throw new CompleXml_Object_Exception ( 'Object not HttpModel' );
		}
		$xmlString = $Object->View->getXml ();
		$file = $Object->View->getTemplate().'.xsl';
		if ($this->getIsDebug ()) {
			header ( "Content-type: text/xml" );
			$xml = new DomDocument ( );
			$xml->loadXML ( $xmlString );
			@$xml->xinclude ();
			echo $xml->saveXML ();
		}
		elseif($this->canBrowserXsltProccess(getenv('HTTP_USER_AGENT'))){
			$xml = new DomDocument ( );
			$xml->loadXML ( $xmlString );
			@$xml->xinclude ();
			$outputXml = $xml->saveXML ();
			$outputXml = str_replace('?>', '?><?xml-stylesheet type="text/xsl" href="'.$file.'"?>', $outputXml);
			header ( "Content-type: text/xml" );
			$Object->Response->nocache ();
			echo $outputXml;
		}else{
			$xsl = new DomDocument ( );
			$xsl->load ( $file );

			$xml = new DomDocument ( );
			$xml->loadXML ( $xmlString );
			@$xml->xinclude ();

			$proc = new XsltProcessor ( );
			$xsl = $proc->importStylesheet ( $xsl );

			$newDom = $proc->transformToDoc ( $xml );

			$str = $newDom->saveHTML ();

			$Object->Response->nocache ();

			echo $str;
		}
	}
}